package com.chashu.baidumapservice;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;

import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.GeoPoint;
import com.baidu.mapapi.LocationListener;
import com.baidu.mapapi.MKSearch;

import android.app.Service;
import android.content.Intent;
import android.location.Location;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;

public class GetLocationService extends Service {
	
	//private MyLocation my_location;
	private static final String FILENAME = "data.txt";
	
	protected static final String TAG = null;
	LocationListener mLocationListener = null;
	BMapApiDemoApp app = null;
	@Override
	public void onCreate() {
		super.onCreate();
		app = (BMapApiDemoApp) this.getApplication();
		if (app.mBMapMan == null) {
			app.mBMapMan = new BMapManager(getApplication());
			app.mBMapMan.init(app.mStrKey,
					new BMapApiDemoApp.MyGeneralListener());
		}
		app.mBMapMan.start();
		final MKSearch mMKSearch = new MKSearch();
		mMKSearch.init(app.mBMapMan, new GeoCoderParser());

		// 注册定位事件
		mLocationListener = new LocationListener() {

			@Override
			public void onLocationChanged(Location location) {
				Log.d(TAG, "location change");
				if (location != null) {
					String strLog = String.format("经度:%f\r\n" + "纬度:%f", 
							location.getLongitude(),
							location.getLatitude());
					
					//my_location = new MyLocation(location.getLongitude(),location.getLongitude());
					String str = String.format("经度:%f " + "纬度:%f\r\n", 
							location.getLongitude(),
							location.getLatitude());
					Log.d(TAG, strLog);
					try {
						saveData(str);
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					GeoPoint point = new GeoPoint((int)(location.getLatitude() * 1E6), (int)(location.getLongitude() * 1E6));
					mMKSearch.reverseGeocode(point);
					
					app.mBMapMan.getLocationManager().removeUpdates(mLocationListener);
					app.mBMapMan.stop();
				}
			}
		};
	}
	
	public void saveData(String str) throws IOException {

		File sdCard = Environment.getExternalStorageDirectory();
		// 获取外部存储设备（SD卡）的路径
		Log.i(TAG, sdCard.getAbsolutePath());
		// 查看LogCat,获取的sd卡的绝对路径为 /storage/sdcard
		sdCard = new File(sdCard, "/MyFiles");
		sdCard.mkdirs();// 创建MyFiles目录(可创建多级目录)
		sdCard = new File(sdCard, FILENAME);
		FileOutputStream out = new FileOutputStream(sdCard,true);
		Writer writer = new OutputStreamWriter(out);
		try {
			writer.write(str);
		} finally {
			writer.close();
		}
	}

	@Override
	public int onStartCommand(Intent intent, int flag, int startId) {
		app.mBMapMan.getLocationManager().requestLocationUpdates(
				mLocationListener);
		app.mBMapMan.start();
		return Service.START_NOT_STICKY;
	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

}
